package com.heima.item.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.item.pojo.Item;
import com.heima.item.pojo.ItemStock;
import com.heima.item.service.IItemStockService;
import com.heima.item.service.impl.ItemService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisHandler implements InitializingBean {
    //自带的json序列化工具
    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ItemService itemService;
    @Autowired
    private IItemStockService iItemStockService;

    /**
     * 缓存预热
     * 实现InitializingBean的afterPropertiesSet方法
     * 在这个类Bean初始化完成后就会进行方法中的操作
     * 我们在这个方法中进行缓存预热
     * 即将热点数据取出放入redis，避免服务刚启动时热点数据没有缓存被打崩
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        //1. 查询商品信息
        List<Item> list = itemService.list();
        //2.放入缓存
        for (Item item : list) {
            //序列化为json存入redis
            String json = MAPPER.writeValueAsString(item);
            redisTemplate.opsForValue().set("item:id:" + item.getId(), json);
        }
        //3. 查询库存信息
        List<ItemStock> stockList = iItemStockService.list();
        //4.放入缓存
        for (ItemStock item : stockList) {
            //序列化为json存入redis
            String json = MAPPER.writeValueAsString(item);
            redisTemplate.opsForValue().set("item:stock:id:" + item.getId(), json);
        }
    }

    /**
     * redis保存逻辑
     *
     * @param item
     */
    public void saveItem(Item item) {
        //序列化为json存入redis
        String json = null;
        try {
            json = MAPPER.writeValueAsString(item);
            redisTemplate.opsForValue().set("item:id:" + item.getId(), json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * redis保存逻辑
     *
     * @param id
     */
    public void delItem(Long id) {
        redisTemplate.delete("item:id:" + id);

    }
}
